<?php

namespace app\admin\controller;

use app\models\{Region, Subcate, Product,Ecsource};
use think\Controller;
use think\facade\Env;
use think\Db;
use oss\Oss;
use app\facade\Redis;

class Base extends Controller
{

    public function initialize() {}

    public function getecsource()
    {
        $type = $this->request->get('type/d', 0); //关键词
        $eclaiyuan = (new Ecsource())->where(['type' => $type])->select() ?? [];
        return json(['code' => 0, 'data' => $eclaiyuan]);
    }

    public function getaddress()
    {
        $keyword = $this->request->get('keyword/s', ''); //关键词
        if (empty($keyword)) {
            return json(['code' => 0, 'data' => []]);
        }
        $url = 'https://apis.map.qq.com/ws/place/v1/suggestion';
        $result = api_curl($url, ['keyword' => $keyword, 'key' => 'UHRBZ-EYNKG-MKSQO-IEY66-FHOGV-W3FKM']);
        if (!empty($result) && $result['status'] == 0 && count($result['data']) > 0) {
            return json(['code' => 0, 'data' => $result['data']]);
        }
        return json(['code' => 1, 'data' => []]);
    }

    public function getproduct()
    {
        $agentid = $this->request->get('agentid/d', ''); //关键词
        if (empty($agentid)) {
            return json(['code' => 1, 'data' => []]);
        }
        $list = (new Product())->where(['agentid' => $agentid, 'isdel' => 1])->field('id,title,price')->select();
        return json(['code' => 200, 'data' => $list]);
    }

    protected function get_rand_str($len = 6)
    {
        $arr = array_merge(range(0, 9), range('a', 'z'), range('A', 'Z'), array('$', '@', '#', '%', '&'));
        shuffle($arr);
        $sub_arr = array_slice($arr, 0, $len);
        return implode('', $sub_arr);
    }

    //图片上传
    public function upload_img()
    {
        if ($this->request->isPost()) {
            if (Env::get('aliyun.open')) {
                if (empty($_FILES['file'])) {
                    return json(['code' => 1, 'status' => 1, 'msg' => '参数错误']);
                }
                $file = $_FILES['file'];
                $oss = new Oss();
                $oss->setUploadType('ram');
                $url = $oss->uploadPostFile($file, 'ming_user/' . date('Y-m-d'));
                return json(['code' => 200, 'msg' => '操作成功', 'url' => $url]);
            } else {
                $file = request()->file('file');
                $path =  $_SERVER['DOCUMENT_ROOT'] . "/uploads/";
                $info = $file->validate(['ext' => 'jpg,png,gif,jpeg'])
                    ->move($path);
                if (!$info) {
                    return json(['code' => 1, 'msg' => $file->getError(), 'data' => []]);
                } else {
                    $file_edit = $info->getInfo();
                    $url = './uploads' . '/' . date("Ymd") . '/' . $info->getfileName();
                    if ($file_edit['size'] > 204800) { // 大于100K的图片进行处理
                        // 获取上传的图片，进行图片压缩
                        $image = \think\Image::open($info);
                        // 保存图片的路径处理
                        $image->thumb(1400, 1400)->save($url);
                    }
                    $url = url($url, '', '', false);
                    $url = "https://" . Env('app.api_url') . $url;
                    return json(['code' => 200, 'msg' => '操作成功', 'url' => $url]);
                }
            }
        }
    }

    public function authorities()
    {
        $arr = [
            'authGroup' => [],
            'authPrivate' => [],
            'supersAdmin' => [],
            'authorities' => [],
        ];
        $menu1 = config('menu.menu');
        $menu = [];
        $admin = $this->request->admin;
        foreach ($menu1 as $k => $v) {
            if ($v['show'] == true) {
                foreach ($v['sub'] as $x => $y) {
                    if (($y['show'] == true && in_array($y['uri'], $admin['role'])) || $admin['is_default'] == 1) {
                        $menu[$k]['name'] = $v['name'];
                        $menu[$k]['ico'] = $v['ico'];
                        $menu[$k]['show'][$x] = $v['show'];
                        $menu[$k]['sub'][$x] = $y;
                    }
                }
            }
        }
        $controller = strtolower($this->request->controller());
        $action = strtolower($this->request->action());
        $path = [];
        if (isset($menu[$controller])) {
            $path['c'] = $menu[$controller]['name'] ?: null;
            $path['a'] = $menu[$controller]['sub'][$action]['name'] ?: null;
            $path['s'] = $menu[$controller]['sub'][$action]['show'] ?: null;
        }
        foreach ($menu as $k => $menus) {
            if ($menus['show']) {
                $arr['authorities'][$k] = [
                    'id' => $k,
                    'title' => $menus['name'],
                    'router' => "#",
                    "alias" => "#",
                    "type" => 0,
                    "note" => null,
                    "condition" => "",
                    "sort" => 0,
                    "icons" => $menus['ico'],
                    "auth" => 0,
                    "status" => "normal",
                    "isSystem" => 0,
                    "children" => []
                ];
                foreach ($menus['sub'] as $ks =>  $m) {
                    if ($m['show']) {
                        $arr['authorities'][$k]['children'][$ks] = [
                            "id" => 2,
                            "pid" => $k,
                            "title" => $m['name'],
                            "router" => $m['uri'],
                            "type" => 0,
                            "sort" => 1
                        ];
                    }
                }
            }
        }
        return json($arr);
    }


    //获取行政
    public function getregion()
    {
        $data = $this->request->get();
        if (empty($data['area_code']) || empty($data['level'])) {
            return json(['code' => 1, 'msg' => '参数信息错误']);
        }
        $pparent = [];
        $parent = (new Region())->where(['level' => ($data['level'] - 1), 'area_code' => $data['area_code']])->find() ?? [];
        if (empty($parent)) {
            return json(['code' => 1, 'data' => [], 'parent' => [], 'msg' => '找不到上级区域']);
        }
        $list = (new Region())->where(['level' => $data['level'], 'parent_id' => $parent['id']])->select();
        if (empty($list)) {
            return json(['code' => 1, 'data' => [], 'parent' => [], 'msg' => '找不到下级区域列表']);
        }
        if ($data['level'] == 4 &&  !empty($data['isget'])) {
            $pparent = (new Region())->where(['level' => ($data['level'] - 2), 'id' => $parent['parent_id']])->find() ?? [];
        }
        return json(['code' => 200, 'data' => $list, 'parent' => $parent, 'pparent' => $pparent]);
    }

    //获取子分类
    public function subcate()
    {
        $cate = $this->request->get('cate/d', 0);
        if (empty($cate)) {
            return json(['code' => 1, 'msg' => '参数信息错误']);
        }
        $agentid = $this->request->get('agentid/d', 0);
        $where = array();
        $where[] = ['cate', '=', $cate];
        if (!empty($agentid)) {
            $where[] = ['agentid', '=', $agentid];
        } else {
            $where[] = ['agentid', '=', 0];
        }
        $list = (new Subcate())->where($where)->select();
        return json(['code' => 200, 'data' => $list]);
    }
}
